<template>
  <xtx-dialog @closed="closedHandler" title="取消订单" v-model:visible="visibleDialog">
    <!-- 组件内容 -->
    <div class="cancel-info">
      <p>取消订单后，本单享有的优惠可能会一并取消，是否继续？</p>
      <p class="tip">请选择取消订单的原因（必选）：</p>
      <div class="btn">
        <a @click="cancelReasonItem = item" :class="{ active: cancelReasonItem === item }" v-for="item in cancelReason"
          :key="item" href="javascript:;">{{ item }}</a>
      </div>
    </div>
    <!-- 按钮操作 -->
    <template #footer>
      <xtx-button type="gray" @click="closedHandler" style="margin-right:20px">取消</xtx-button>
      <xtx-button type="primary" @click="submitCancelReason">确认</xtx-button>
    </template>
  </xtx-dialog>
</template>
<script setup>
import { ref, defineExpose, inject } from 'vue'
import { cancelReason } from '@/config'
import Message from '@/components/library/message'
import { cancelOrderApi } from '@/api/order'
const visibleDialog = ref(false)
// 向外暴露一个open方法来打开对话框
function open() {
  visibleDialog.value = true
}
defineExpose({
  open
})
// 关闭对话框的处理事件
function closedHandler() {
  visibleDialog.value = false
  cancelReasonItem.value = null
}

// 获取订单数据
const order = inject('order')
// 定义取消原因
const cancelReasonItem = ref(null)
// 提交取消原因
function submitCancelReason() {
  if (cancelReasonItem.value === null) {
    return Message({ text: '请至少选择一个理由进行取消' })
  }
  cancelOrderApi(order.id, cancelReasonItem.value).then(() => {
    Message({ type: 'success', text: '取消成功' })
    visibleDialog.value = false
    // 去修改该条订单的订单状态(利用order对象是引用数据类型，可以直接修改)
    order.orderState = 6
  }).catch(err => {
    Message({ type: 'error', text: err.response.data.message })
  })
}

</script>
<style scoped lang="less">
.xtx-dialog :deep(.wrapper) {
  width: 620px !important;
}

.cancel-info {
  p {
    font-size: 16px;
    line-height: 35px;

    &.tip {
      color: #999;
    }
  }

  .btn {
    padding-top: 21px;
    display: flex;
    flex-wrap: wrap;

    a {
      width: 256px;
      height: 45px;
      line-height: 45px;
      text-align: center;
      background-color: #ffffff;
      border: 1px solid #e4e4e4;
      margin-right: 20px;
      margin-bottom: 20px;
      color: #666;

      &:nth-child(2n) {
        margin-right: 0;
      }

      &:hover,
      &.active {
        background-color: #e3f9f4;
        border-color: @xtxColor;
      }
    }
  }
}
</style>